package com.zige.zige.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.CheckUtils;
import com.zige.zige.utils.NetworkUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.view.TimeButton;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by Fei on 2015/11/5.
 * 忘记密码
 */
public class RetrievePasswordActivity extends BaseActivity implements View.OnClickListener{

    private Activity activity;;
    private LinearLayout lay_back;
    private TextView tv_titlet;
    private Button btn_accordingTo,btn_getCode,btn_commit;
    private EditText phoneNumber,newPassword,verificationCode;
    private boolean isShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_password);
        activity = this;
        initView();

    }
    private void initView(){
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(this);
        tv_titlet= serchViewById(R.id.title_name);
        tv_titlet.setText("找回密码");

        phoneNumber = serchViewById(R.id.ed_phoneNumber);
        phoneNumber.addTextChangedListener(textWatcher);
        verificationCode = serchViewById(R.id.ed_fount_code);
        verificationCode.addTextChangedListener(textWatcher);
        newPassword = serchViewById(R.id.ed_newPassword);
        newPassword.addTextChangedListener(textWatcher);


        btn_getCode = serchViewById(R.id.btn_getCode);
        btn_getCode.setOnClickListener(this);
        btn_accordingTo = serchViewById(R.id.btn_accordingTo);
        btn_accordingTo.setOnClickListener(this);
        btn_commit = serchViewById(R.id.btn_commit);
        btn_commit.setEnabled(false);
        btn_commit.setOnClickListener(this);
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if(TextUtils.isEmpty(phoneNumber.getText())||TextUtils.isEmpty(verificationCode.getText())||TextUtils.isEmpty(newPassword.getText())){
                btn_commit.setEnabled(false);
                btn_commit.setBackgroundResource(R.drawable.registered_btn_comit);

            }else {
                btn_commit.setEnabled(true);
                btn_commit.setBackgroundResource(R.drawable.bg_btn_selector);
            }

        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.lay_back:
                RetrievePasswordActivity.this.finish();
                break;
            case R.id.btn_accordingTo:
                isShow(newPassword);

                break;
            case R.id.btn_getCode:
                if(TextUtils.isEmpty(phoneNumber.getText().toString())){
                    showErrorDialog("手机号码还未填写");
                    return;
                }
                if(!CheckUtils.isMobile(phoneNumber.getText().toString())){
                    showErrorDialog("手机号码不正确");
                    return;
                }

                if(NetworkUtils.isNetworkAvailable(activity)){

                    getCode(phoneNumber.getText().toString());
                }else {
                    showErrorDialog("请求失败请检查您的网络");
                }
                break;
            case R.id.btn_commit:
                String phone = phoneNumber.getText().toString();
                String code = verificationCode.getText().toString();
                String password = newPassword.getText().toString();
                if(TextUtils.isEmpty(phone)){
                    showErrorDialog("手机号码还未填写");
                    return;
                }
                if(!CheckUtils.isMobile(phone)){
                    showErrorDialog("手机号码不正确");
                    return;
                }
                if(TextUtils.isEmpty(code)){
                     showErrorDialog( "验证码还未填写");
                    return;
                }
                if(TextUtils.isEmpty(password)){
                     showErrorDialog( "密码还未填写");
                    return;
                }
                if(password.length()<6){
                     showErrorDialog( "密码位数不能少于6位");
                    return;
                }

                if(NetworkUtils.isNetworkAvailable(activity)){
                    commit(phone, password, code);
                }else {
                     showErrorDialog( "请求失败请检查您的网络");
                }

                break;
        }
    }
    private void getCode(String phone){
        String type = "1";
        HashMap<String,String> params = new HashMap<>();
        params.put("phone",phone);
        params.put("type",type);
        params.put("deviceId", SystemUtils.getDeviceKey(this));
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params,activity, UrlConsts.GET_CODE) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code =object.getInt("code");
                    String msg = object.getString("message");
                   closeLoadingDialog();
                    if(code==0000){
                        closeLoadingDialog();
                         showErrorDialog( "验证码已发送到您的手机");
                        TimeButton timerButton = new TimeButton(RetrievePasswordActivity.this, 60000,1000,btn_getCode);
                        timerButton.start();
                    }else{
                        throw new Exception(msg);
                    }
                }catch (Exception e) {
                     showErrorDialog("获取验证码失败");
//                    tv_check_error.setVisibility(View.VISIBLE);
                }finally {
                    closeLoadingDialog();
                }
            }
                                           }

        );
    }

    private void commit(String phone,String password,String code){

        HashMap<String,String> params = new HashMap<>();
        params.put("phone",phone);
        params.put("password",password);
        params.put("verifyCode",code);
            showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, UrlConsts.USER_RETRIEVE_PASSWORD) {
                                               @Override
                                               protected void handleResponse(String response) {
                                                   try {
                                                       JSONObject object = new JSONObject(response);
                                                       int code = object.getInt("code");
                                                       String msg = object.getString("message");
                                                       closeLoadingDialog();
                                                       if (code == 0000) {
                                                            showErrorDialog( "修改密码成功");
                                                           startActivity(new Intent(RetrievePasswordActivity.this,RegisterActivity.class));
                                                           finish();
                                                           overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
                                                       } else {
                                                           throw new Exception(msg);
                                                       }
                                                   } catch (Exception e) {
                                                        showErrorDialog( e.getMessage());
                                                   } finally {
                                                    closeLoadingDialog();
                                                   }
                                               }
                                           }
        );

    }


    /**
     * 隐藏或显示密码
     */
    private void isShow(EditText password){

        if(isShow){
            password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            btn_accordingTo.setText("隐藏");
        }else {
            password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            btn_accordingTo.setText("显示");
        }
        isShow = !isShow;
        password.postInvalidate();
        CharSequence charSequence = password.getText();
        if(charSequence instanceof Spannable){
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }
}
